package org.ilead.iserve.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.ilead.iserve.common.CookiesHelper;
import org.ilead.iserve.common.email.AuditEmailTemplate;
import org.ilead.iserve.common.email.HtmlEmailSender;
import org.ilead.iserve.common.email.RegisterEmailTemplate;
import org.ilead.iserve.constants.LopConstants;
import org.ilead.iserve.constants.SessionKeyConstant;
import org.ilead.iserve.model.HomePage;
import org.ilead.iserve.model.User;
import org.ilead.iserve.model.UserPermission;
import org.ilead.iserve.model.UserVerifyAssociate;
import org.ilead.iserve.model.base.PageView;
import org.ilead.iserve.service.IUserPageService;
import org.ilead.iserve.service.IUserService;
import org.ilead.iserve.service.IUserVerifyAssociateService;
import org.ilead.iserve.service.manager.HomePageManager;
import org.ilead.iserve.service.manager.UserManager;
import org.ilead.iserve.service.manager.UserPermissionManager;
import org.ilead.iserve.util.FileUpLoadUtil;
import org.ilead.iserve.web.base.BaseActionSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

public class UserAction extends BaseActionSupport {
	private static final long serialVersionUID = 7853912726475390874L;
	private static final Logger log = LoggerFactory
			.getLogger(UserAction.class);
	private Integer uid = new Integer(0);// 用于修改删除时传参数
	private User u = new User();// 用于增改
	private List<User> userList = new ArrayList<User>();// 用于查询
	private IUserService userService = null;
	private IUserVerifyAssociateService userVerifyAssociateService = null;
	private String userSex;
	
	private File doc;
	private String fileName;
	/**
	 * 用户保存修改用户权限的action传过来的权限值
	 */
	private int permission;
	
	/**
	 * 自动登录的标志
	 */
	private boolean autoLoginFlag;
	
	/**
	 * 校验码
	 */
	private String validateCode = "";
	
	@Autowired
	private IUserPageService userPageService;
	
	public String addUser() throws Exception {
		try {
			userService.addUser(u);
		} catch (Exception e) {
			log.error("保存用户错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public String listUser() throws Exception {
		
		/**
		 * 下面3句固定
		 */
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		int maxResult = 20;
		/**
		 * 修改Bean和service即可
		 */
		PageView<User> pageView = new PageView<User>(maxResult, getPage());
		LinkedHashMap<String, String> orderMap = new LinkedHashMap<String, String>();
		orderMap.put("permission", "");
		
		pageView.setQueryResult(userPageService.getScrollData(pageView.getFirstResult(), maxResult, null,null, orderMap));
		UserManager.getInstance().setUserList(pageView.getRecords());
		
		/**
		 * request.setAttribute("pageView", pageView)中key尽量为pageView，不然需要修改代码
		 */
		request.setAttribute("pageView", pageView);
		return SUCCESS;
	}

	public String editUser() throws Exception {
		try {
			u = userService.findById(uid);
		} catch (Exception e) {
			log.error("修改用户错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public String updateUser() throws Exception {
		try {
			User selectedUser = null;
			for (User user : UserManager.getInstance().getUserList()){
				if(user.getId().equals(uid) && user.getPermission().intValue() != permission){
					user.setPermission(permission);
					selectedUser = user;
					
					userService.updateUser(selectedUser);
					HomePage homePage = HomePageManager.getInstance().getHomePageByUserId(selectedUser.getId());
					if(homePage == null){
						HttpServletRequest request = (HttpServletRequest) 
							ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
						String url = request.getContextPath() + "/homePage.jsp?id=" + UUID.randomUUID().toString();
						HomePageManager.getInstance().saveHomePage(user.getId(), url, "");
						
						//发送审核通过的邮件
						HtmlEmailSender.sendMessage(selectedUser.getEmail(), 
								AuditEmailTemplate.getTitle(selectedUser.getUserName()), AuditEmailTemplate.getContent());
					}
					UserManager.getInstance().updateCacheUserList();
					break;
				}
			}
		} catch (Exception e) {
			log.error("更新用户错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public String delUser() throws Exception {
		try {
			userService.delUserById(uid);
		} catch (Exception e) {
			log.error("删除用户错误", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 用户登录
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		try {
			ActionContext context = ActionContext.getContext();
			String rand = (String)context.getSession().get(SessionKeyConstant.RAND);
			if(!(validateCode.equalsIgnoreCase(rand))){
				context.getSession().put(SessionKeyConstant.ERROR_MESSAGE, "验证码错误");
				return INPUT;
			}
			User loginUser = userService.login(u.getLoginName(), u.getPassword());
			if (null != loginUser && loginUser.getState() != 0 && loginUser.getPermission() > 1) {
				HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
				HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
				UserManager.getInstance().updateSessionAndUser(request, loginUser);
				if(autoLoginFlag)
					CookiesHelper.setUserCookies(request, response, loginUser.getLoginName(), loginUser.getPassword());
				else
					CookiesHelper.clearUserCookies(request, response);
				return SUCCESS;
			} else if(null == loginUser || loginUser.getState() == 0){
				context.getSession().put(SessionKeyConstant.ERROR_MESSAGE, "用户名或密码错误");
			} else{
				context.getSession().put(SessionKeyConstant.ERROR_MESSAGE, "该用户名未通过管理员审核");
			}
		} catch (Exception e) {
			log.error("登录查询错误", e);
			return ERROR;
		}
		return INPUT;
	}
	
	public void loginSuccess() {
		ActionContext ctx = ActionContext.getContext();
		HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE);
		String lastAccessPage = (String)ctx.getSession().get(SessionKeyConstant.LAST_ACCESS_PAGE);
		try {
			if(lastAccessPage == null || "".equals(lastAccessPage))
				response.sendRedirect("index.jsp");
			else{
				response.sendRedirect(lastAccessPage);
			}
		} catch (IOException e) {
			log.error("页面跳转错误:"  + lastAccessPage, e);
		}
	}
	
	/**
	 * 用户注册
	 * @return
	 * @throws Exception
	 */
	public String register() throws Exception {
		try {
			ActionContext context = ActionContext.getContext();
			String rand = (String)context.getSession().get("rand");
			if(!(validateCode.equalsIgnoreCase(rand))){
				addActionError("验证码错误");
				return INPUT;
			}
			u.setRegisterTime(new Date());
			u.setPermission(1);
			userService.addUser(u);
			//暂时屏蔽邮件功能
//			String uuid = UUID.randomUUID().toString() + UUID.randomUUID().toString();
//			HtmlEmailSender.sendMessage(u.getEmail(), RegisterEmailTemplate.getTitle(u.getUserName()), 
//					RegisterEmailTemplate.getContent(u.getId() + "", uuid));
//			userVerifyAssociateService.add(new UserVerifyAssociate(uuid, u.getId()));
		} catch (Exception e) {
			log.error("", e);
			return ERROR;
		}
		return SUCCESS;
	}
	
	/**
	 * 用户邮箱认证
	 * @return
	 * @throws Exception
	 */
	public String verify() throws Exception {
		try {
			ActionContext context = ActionContext.getContext();
			String[] code = (String[])context.getParameters().get("code");
			String[] id = (String[])context.getParameters().get("id");
			UserVerifyAssociate associate = userVerifyAssociateService.findByUserId(Integer.parseInt(id[0]));
			if(associate != null && associate.getCode().equals(code[0])){
				User user = userService.findById(associate.getUserId());
				user.setState(1);
				userService.updateUser(user);
				if(user.getPermission() > 1){
					HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_RESPONSE);
					UserManager.getInstance().updateSessionAndUser(request, user);
				}
				
				return SUCCESS;
			}
		} catch (Exception e) {
			log.error("", e);
			return ERROR;
		}
		return INPUT;
	}
	
	/**
	 * 更新邮箱
	 * @return
	 * @throws Exception
	 */
	public String updateEmail() throws Exception {
		try {
			User user = UserManager.getInstance().getLoginUser();
			user.setEmail(u.getEmail());
			user.setState(0);
			userService.updateUser(user);
			return SUCCESS;
		} catch (Exception e) {
			log.error("", e);
			return ERROR;
		}
	}
	
	public String saveAvatar(){
		try {
			if(doc == null)
				return null;
			
			User user = UserManager.getInstance().getLoginUser();
			String imageFileName = new Date().getTime() + FileUpLoadUtil.getExtention(fileName);
			File imageFile = new File(ServletActionContext.getServletContext()
					.getRealPath(LopConstants.UPLOAD_AVATAR_PATH) + File.separatorChar + imageFileName);
			FileUpLoadUtil.copy(doc, imageFile);
			String oldImage = user.getImage();
			if(oldImage != null && !"".equals(oldImage)){
				String pathName = ServletActionContext.getServletContext().getRealPath("/");
				String oldImagePath = pathName + LopConstants.UPLOAD_AVATAR_PATH + File.separatorChar + oldImage;
				new File(oldImagePath).delete();
			}
				
			user.setImage(imageFileName);
			userService.updateUser(user);
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
			ActionContext.getContext().getSession().put(SessionKeyConstant.AVATAR_URL, UserManager.getInstance().getAvatarUrl(request, user));
			return SUCCESS;
		} catch (Exception e) {
			log.error("", e);
			return ERROR;
		}
	}

	/**
	 * 用户退出
	 * @return
	 * @throws Exception
	 */
	public String logout() throws Exception {
		ActionContext context = ActionContext.getContext();
		Map<String, Object> attibutes = context.getSession();
		attibutes.remove(SessionKeyConstant.LOGIN_USER);
		attibutes.remove(SessionKeyConstant.LAST_ACCESS_PAGE);
		attibutes.remove(SessionKeyConstant.MESSAGE_COUNT);
		HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) context.get(ServletActionContext.HTTP_RESPONSE);
		CookiesHelper.clearUserCookies(request, response);
		request.getSession().invalidate();
		return Action.LOGIN;
	}
	
	/**
	 * 用户管理权限认证
	 * @return
	 * @throws Exception
	 */
	public String manageVerify() throws Exception {
		try {
			return SUCCESS;
		} catch (Exception e) {
			log.warn("", e);
			return INPUT;
		}
	}

	public String beforeAddUser() throws Exception {
		return SUCCESS;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public void setUserVerifyAssociateService(
			IUserVerifyAssociateService userVerifyAssociateService) {
		this.userVerifyAssociateService = userVerifyAssociateService;
	}

	public User getU() {
		return u;
	}

	public void setU(User u) {
		this.u = u;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	public String getUserSex() {
		return userSex;
	}

	public void setUserSex(String userSex) {
		this.userSex = userSex;
		u.setSex(userSex == "男");
	}

	public String getValidateCode() {
		return validateCode;
	}

	public void setValidateCode(String validateCode) {
		this.validateCode = validateCode;
	}

	public void setUsersPageService(IUserPageService userPageService) {
		this.userPageService = userPageService;
	}
	
	public List<UserPermission> getPermissionList(){
		return UserPermissionManager.getInstance().getAll();
	}
	
	public File getDoc() {
		return doc;
	}

	public void setDoc(File doc) {
		this.doc = doc;
	}
	
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setDocFileName(String fileName) {
		this.fileName = fileName;
	}

	public int getPermission() {
		return permission;
	}

	public void setPermission(int permission) {
		this.permission = permission;
	}

	public void setAutoLoginFlag(boolean autoLoginFlag) {
		this.autoLoginFlag = true;
	}
	
}
